import { toSuccess, useEntityManager } from "@sker/core"
import { KsDevice } from "@sker/entities"
import { useData } from "@sker/runtime"
import { z } from "zod"

export default async () => {
    const input = z.object({
        uuid: z.string()
    })
    const body = input.parse(useData())
    return await useEntityManager(async m => {
        const device = await m.findOne(KsDevice, { where: { uuid: body.uuid } })
        if (device) {
            device.setting = device.setting || {};
            return toSuccess(device)
        }
        const entity = m.create(KsDevice, { uuid: body.uuid, name: '', owner: '', setting: {} })
        const { id } = await m.save(KsDevice, entity)
        const createDevice = await m.findOne(KsDevice, { where: { id } })
        return toSuccess(createDevice)
    });
}
